<template>
  <div class="canvas-editor">
    <div class="toolbar">
      <van-button @click="handleFlipY">垂直翻转</van-button>
      <van-button @click="handleRotate">旋转</van-button>
      <van-button @click="undo" :disabled="!canUndo">撤销</van-button>
      <van-button @click="redo" :disabled="!canRedo">重做</van-button>
      <!-- <van-uploader :after-read="handleFileUpload" accept="image/*">
        <van-button>上传图片</van-button>
      </van-uploader>-->
      <input type="file" @change="handleImageUpload" accept="image/*" />
    </div>
    <div class="index">
      <div class="canvas" id="canvas" ref="canvasRef"></div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from "vue";

import Konva from "konva";
const canvasRef = ref<HTMLCanvasElement | null>(null);
let imgNode: Konva.Image | null = null;
let stage: Konva.Stage | null = null;
const layer: Konva.Layer = new Konva.Layer();

const tr: Konva.Transformer = new Konva.Transformer();
const selectedNode = ref<Konva.Image>(); // 新增选中节点引用
const scaleFactor = 1.1; // 缩放系数
const handleRotate = () => {
  if (imgNode) {
    // 每次旋转90度（基于当前旋转角度）
    const currentRotation = imgNode.rotation();

    imgNode.rotation((currentRotation + 90) % 360);
    layer.batchDraw();
  }
};
const handleFlipY = () => {
  if (imgNode) {
    // 简化翻转逻辑，直接修改scaleX并调整位置
    // const currentScale = imgNode.scaleX();
    // imgNode.scaleX(-currentScale);
    // 调整位置保持图片中心不变
    // imgNode.x(imgNode.x() + imgNode.width() * currentScale);
    imgNode.scaleX(imgNode.scaleX() * -1);
    layer.batchDraw();
  }
}; // 新增翻转Y轴功能
// 初始化Canvas
onMounted(() => {
  const { clientWidth, clientHeight } = canvasRef.value || {
    clientWidth: 0,
    clientHeight: 0
  };
  stage = new Konva.Stage({
    container: "canvas",
    width: clientWidth,
    height: clientHeight
  });
  stage.add(layer);

  // stage.on("click tap", (e) => {
  //   console.log('stage click', e);
  //   const dom = e.target
  //   console.log('dom', dom.getType())
  //   if (dom.getType() === "Shape") {//点击的是图形，Stage是画布，清空
  //     tr.nodes([dom])
  //   } else {
  //     tr.nodes([])
  //   }
  // })

  // const selectionRect = new Konva.Rect({
  //   fill: "rgba(0,0,255,0.1)",

  //   visible: false,
  //   stroke: "rgba(0,0,255,0.5)",
  //   strokeWidth: 1,
  // })
  // layer.add(selectionRect)
  // layer.add(tr)

  // init();
});
const init = () => {
  const el = document.getElementById("canvas");
  if (!el) {
    return;
  }

  const { clientWidth, clientHeight } = el;
  const stage = new Konva.Stage({
    container: "canvas",
    width: clientWidth,
    height: clientHeight
  });

  const layer = new Konva.Layer();
  stage.add(layer);

  Konva.Image.fromURL("/src/assets/tabbar/edit.png", (image: Konva.Image) => {
    image.setAttrs({
      x: clientWidth / 2 - 25,
      y: clientHeight / 2 - 25,
      height: 50,
      width: 50,
      scaleY: 1,
      scaleX: 1
    });

    layer.add(image);
  });
};
const handleImageUpload = (e: Event) => {
  const file = (e.target as HTMLInputElement).files?.[0];
  if (file) {
    const reader = new FileReader();
    reader.onload = e => {
      const image = new Image();
      image.src = e.target?.result as string;
      image.onload = () => {
        const group = new Konva.Group();

        imgNode = new Konva.Image({
          image: image,
          draggable: true,
          x: 50,
          y: 50,
          width: 100,
          height: 100,
          offset: {
            // offset的设置是使得围绕中心旋转：x:50,y:50
            x: 50,
            y: 50
          }
        });
        console.log("imgNode", imgNode);

        layer.add(imgNode);

        console.log("imgNode.x", imgNode.x()); //70
        console.log("imgNode.widdth()", imgNode.width()); //100

        // 创建右下角旋转手柄
        const rotateHandle = new Konva.Circle({
          // x: 120,  // 初始位置：x + width
          // y: 120,  // 初始位置：y + height
          x: imgNode.width(), // 初始位置：x + width
          y: imgNode.height(), // 初始位置：y + height
          radius: 8,
          fill: "rgba(255,0,0,0.6)",
          draggable: true
        });

        // 新增组变换监听
        group.on("transform dragmove", () => {
          rotateHandle.position({
            x: imgNode.width(),
            y: imgNode.height()
          });
        });

        // 旋转逻辑
        let startAngle = 0;
        rotateHandle.on("dragstart", () => {
          const absPos = group.getAbsolutePosition();
          console.log("点击手柄", absPos);
          const center = {
            x: absPos.x + imgNode.width() / 2,
            y: absPos.y + imgNode.height() / 2
          };
          const pos = rotateHandle.getStage()?.getPointerPosition();
          console.log("pos", pos);
          if (pos) {
            const newAngle = Math.atan2(pos.y - center.y, pos.x - center.x);
            if (e.type === "dragstart") {
              startAngle = newAngle;
            } else {
              imgNode.rotation((newAngle - startAngle) * (180 / Math.PI));
              layer.batchDraw();
            }
          }
        });

        rotateHandle.on("dragmove", () => {
          console.log("移动手柄");
          const center = {
            x: imgNode.x() + imgNode.width() / 2,
            y: imgNode.y() + imgNode.height() / 2
          };
          const pos = rotateHandle.getStage()?.getPointerPosition();
          if (pos) {
            const newAngle = Math.atan2(pos.y - center.y, pos.x - center.x);
            imgNode.rotation((newAngle - startAngle) * (180 / Math.PI));
            layer.batchDraw();
          }
        });

        // 将图片和手柄组合

        group.add(imgNode);
        group.add(rotateHandle);
        layer.add(group);

        // var triggerTime = -1000;
        // var scale = 1;
        // var angularSpeed = 190;
        // var anim = new Konva.Animation(function(frame: any) {
        //     if (frame.time - triggerTime < 1000){
        //         return false;
        //     }

        //     triggerTime = frame.time;

        //     var angleDiff = frame.timeDiff * angularSpeed / 1000;
        //     scale *= -1;
        //     imgNode.scale({x: scale, y: 1});
        //     // kImage1.rotate(angleDiff);          // 旋转
        //     // kImage2.scale({x: scale, y: 1});    // 左右镜像
        //     // kImage3.scale({x: 1, y: scale});    // 上下翻转
        // }, layer);
        // anim.start();
        // saveHistory('上传图片');
      };
    };
    reader.readAsDataURL(file);
  }
};
</script>

<style lang='scss' scoped>
.index {
  // padding: 20px;

  .canvas {
    background-color: #eee;
    border: 1px solid #666;
    height: calc(50vh);
  }
}
</style>
